package com.baidu.controller;

import com.alibaba.fastjson2.util.DateUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class SseController {
    private static final Map<String,SseEmitter> sseEmitterMap = new ConcurrentHashMap<>();
    @GetMapping("/sse/{uid}")
    public SseEmitter crateSse(@PathVariable  String uid) {
        SseEmitter sseEmitter = new SseEmitter(0L);
        sseEmitter.onCompletion(() -> {
            log.info("[{}]连接断开" , uid);
            sseEmitterMap.remove(uid);
        });
        sseEmitter.onTimeout(() -> {
            log.info("[{}]连接超时",uid);
        });
        sseEmitter.onError(throwable -> {
            log.info("[{}]连接异常，{}",uid,throwable.toString());
            sseEmitterMap.remove(uid);
        });
        try{
            sseEmitter.send(SseEmitter.event().data("Connection successful"));
        }catch (IOException e){
            e.printStackTrace();
        }
        sseEmitterMap.put(uid,sseEmitter);
        log.info("[{}]创建sse连接成功!",uid);
        return sseEmitter;
    }

    @GetMapping("/send/msg/{uid}")
    public boolean sendMessage(@PathVariable String uid){
        SseEmitter sseEmitter = sseEmitterMap.get(uid);
        if(sseEmitter == null){
            log.info("[{}]sse连接不存在",uid);
            return  false;
        }
        try{
            for (int i = 0; i < 10; i++) { // 这里替换为百度智能云流式结果迭代器
                String msg = DateUtils.toString(new Date());
                sseEmitter.send(SseEmitter.event().data(msg));
                log.info("用户{}, 推送成功：{}",uid,msg);
                Thread.sleep(1000);
            }
            return true;
        }catch (Exception e){
            sseEmitterMap.remove(uid);
            log.info("用户{}, 消息推送失败",uid);
            sseEmitter.complete();
            return false;
        }
    }
}
